package com.jiankangjin.pay.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jiankangjin.encryptKit.EncryptUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * Created by rishon on 2014/7/10.
 */
@Controller
public class Handler {

    public static final String TOKEN = "weixin";

    @RequestMapping("/handler")
    public
    @ResponseBody
    String checkToken(@RequestParam String echostr, @RequestParam String signature, @RequestParam String timestamp,
                      @RequestParam String nonce) {

        System.out.println("input param ====== " +
                        "echostr=" +echostr+
                        ", signature=" +signature+
                        ", timestamp=" +timestamp+
                        ", nonce="+nonce
        );
        if (checkSignature(echostr, signature, timestamp, nonce)) {

            return echostr;
        }
        return "";
    }

    public boolean checkSignature(String echo, String sign, String time, String nonce) {

        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String[] arr = new String[]{TOKEN, time, nonce};
        Arrays.sort(arr);
        String tmpStr = "";
        for (String tmp : arr)
            tmpStr = tmpStr + tmp;
        String sha = EncryptUtil.sha(tmpStr);

        if (sha.equalsIgnoreCase(sign))
            return true;
        return false;
    }

    public static void main(String[] arg) {
        System.out.println("start ---------------");
        String[] arr = new String[]{"Aa3", "1234", "Ab3", "a3"};
        for (String tmp : arr)
            System.out.println(tmp);
        System.out.println("do2 ---------------");
        Arrays.sort(arr);
        for (String tmp : arr)
            System.out.println(tmp);
        System.out.println("END ---------------");
    }
}

